package ld.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ld.pojo.Emp;
import ld.service.EmpService;
import ld.utils.PageResult;
import ld.utils.R;
import ld.vo.EmpVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-08-09-19:20
 * @Description:
 */
@WebServlet("/emp")
public class EmpServlet extends HttpServlet {
    @Autowired
    private EmpService empService;

    @Override
    public void init() throws ServletException {
        //在servlet容器取得spring容器（你没有容器怎么取bean？啊啊啊）
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //从spring容器得到bean
        empService = webApplicationContext.getBean(EmpService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到请求参数
        String cmd = req.getParameter("cmd");
        //根据参数调用不同方法
        if (!StringUtils.isEmpty(cmd)){
            if ("query".equals(cmd)){
                query(req,resp);
            }
        }

    }

    private void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //得到分页参数
        String pagestr = req.getParameter("page");
        String pagesizestr = req.getParameter("pagesize");
        //转换为整数或提供默认值
        int page = StringUtils.isEmpty(pagestr) ? 1 : new Integer(pagestr);
        int pagesize = StringUtils.isEmpty(pagesizestr) ? 1 : new Integer(pagesizestr);
        //得到查询对象
        String empsearch = req.getParameter("empsearch");
        if (StringUtils.isEmpty(empsearch)){
            //处理乱码
            String s = new String(empsearch.getBytes("ISO8859-1"), "UTF-8");
            //转换为员工对象
            EmpVo vo = JSON.parseObject(s, EmpVo.class);
            //开始查询
            PageResult<Emp> emps =  empService.search(page,pagesize,vo);
            //输出并刷新
            resp.getWriter().println(JSON.toJSONString(R.ok().data("emps",emps)));
            resp.getWriter().flush();
        }
    }
}
